<?php
/**
 * m()->helper('name');
 * m()->helper()->name();
 *
 */
class lib_helper extends lib_milkphp_library{
	/**
	 * helper存放地址
	 */
	static $helperDir;
	
	/**
	 * 返回对应的lib_data实例
	 * @param String $name
	 */
	static function _do($name=null){
		if(!preg_match("/^[a-z|0-9|A-Z|_]+$/",$name)&&!empty($name))return;
		static $instance=null;
        if (is_null($instance)){
        	$instance= new lib_helper();
        }
        if(empty($name)){
        	return $instance;
        }
        return $instance->getHelper($name);
	}
	
	private function __construct(){
		/**
		 * 注册autoload,自动加载controller
		 */
		spl_autoload_register(array('lib_helper','autoload'));
	}
	
	/**
	 * 自动加载model文件
	 */
	private static function autoload($class){
		if('helper_' != substr($class,0,7))return;
		$helperDir = empty(m()->dir['helper'])?M_DIR.'helper/':m()->dir['helper'];
		$file= str_replace('helper_',$helperDir,$class);
		$file= str_replace('_','/',$file).'.php';
		if(@include($file)){
			milkphp()->debug('i',"include 文件 $file");
		}else{
			milkphp()->debug('e',"文件 $file 不存在");
		}
	}
	
	function getHelper($name,$arguments=array()){
		if(empty($name))return $this;
		$helperName = 'helper_'.$name;
		if(method_exists($helperName,'_do')){
			return call_user_func_array(array($helperName,"_do"),$arguments);
		}
		return new $helperName();
	}
	
	function __call($name,$arguments){
		return $this->getHelper($name,$arguments);
	}
}